import React, { Component } from 'react';
import PubSub from 'pubsub-js'
import { meshLog, SPRemove, SPGet, SPSet } from '../../config';
import { DEVICE_SET_DIALOG_SHOW, DEVICE_SET_DIALOG_HIDE, Regular, CUR_AREA_NO, webHeight } from '../../const/infoConst';
import "./devices.less";
import {
  getNameBygroupID, decimalToVersionString, decimalToVersionString2
} from '../../utils/deviceUtils';
import {
  sumHexBytes, transIntToHex4Str, getOctets2Msg,
  bigEndianToLittleEndian, transIntToHex2Str
} from '../../utils/dataUtils'

import Refresh from './refresh/refresh';

export default class Devices extends Component {
  constructor(a) {
    super(a);
    this.state = {
      currentItems: [],//当前页码的数据
      currentPage: 1,//当前的页码
      totalPages: 0,//所有的页码总数
      itemsPerPage: 15,//每页展示多少数据
      itemsdataALL: [],//所有的数据
      like: [],
      reply: [],
      movetime: '',
      showrefresh: 'hidden',
    }
  }
  componentWillUnmount() {
    PubSub.unsubscribe(DEVICE_SET_DIALOG_SHOW);
    PubSub.unsubscribe(DEVICE_SET_DIALOG_HIDE);
    PubSub.unsubscribe(CUR_AREA_NO);
  }
  componentDidMount() {
    //拿到所有的数据
    const nodes = JSON.parse(SPGet("nodes"))
    meshLog('nodes', nodes);
    //获取数据
    let line = ''
    let page = 1
    let items = 15
    let itemsdata = nodes.slice(0, 15)
    meshLog('voiceInfo', itemsdata);
    // 计算总页数
    let itemsPerPage = this.state.itemsPerPage
    meshLog('每页的个数', itemsPerPage);
    const totalPages = Math.ceil(nodes.length / itemsPerPage);
    meshLog('总的页数', totalPages);
    let currentPage = page //默认显示第一个页码的数据
    const currentItems = itemsdata;
    this.setState({
      currentPage: currentPage,
      totalPages: totalPages,
      itemsdata: itemsdata,
      currentItems: currentItems,
      itemsdataALL: nodes,

    })


  }

  goToPage = async (page) => {
    meshLog('当前展示的page', page);
    let line = ''
    let items = 15
    const nodes = JSON.parse(SPGet("nodes"))
    let itemsdata = nodes.slice((page - 1) * 15, 15 * page)
    meshLog('result', nodes);

    // 计算总页数
    let itemsPerPage = this.state.itemsPerPage
    meshLog('itemsPerPage', itemsPerPage);
    const totalPages = Math.ceil(nodes.length / itemsPerPage);
    meshLog('totalPages', itemsdata);
    let currentPage = page //默认显示第一个页码的数据
    const currentItems = itemsdata;
    this.setState({
      currentPage: currentPage,
      totalPages: totalPages,
      itemsdata: itemsdata,
      currentItems: currentItems,
      itemsdataALL: nodes,
    })

  };

  // 首页
  gotoFirstPage = () => {
    if (this.state.currentPage <= 1) {
      return
    } else {
      let currentPage = 1
      this.setState({
        currentPage: 1,
      })
      this.goToPage(1);
    }

  };
  // 上一页
  goToPreviousPage = () => {
    if (this.state.currentPage <= 1) {
      return
    } else {
      let currentPage = this.state.currentPage
      this.setState({
        currentPage: currentPage - 1,
      })
      this.goToPage(currentPage - 1);
    }

  };
  // 下一页
  goToNextPage = () => {
    if (this.state.currentPage >= this.state.totalPages) {
      return
    } else {
      let currentPage = this.state.currentPage
      this.setState({
        currentPage: currentPage + 1,
      })
      this.goToPage(currentPage + 1);
    }
  };

  // 末页
  goToEndPage = () => {
    if (this.state.currentPage >= this.state.totalPages) {
      return
    } else {
      let currentPage = this.state.totalPages
      this.setState({
        currentPage: currentPage,
      })
      this.goToPage(currentPage);
    }
  };
  // 选择页确定
  changeTOPage = () => {
    var inputElement = document.getElementById('inputid');
    let inputValue = inputElement.value;
    let currentPage = 0
    meshLog('inputValue', inputValue);
    if (inputValue >= this.state.totalPages) {
      inputElement.value = this.state.totalPages
      currentPage = this.state.totalPages
    } else {
      currentPage = parseInt(inputValue)//强制转换成数字类型
    }
    this.setState({
      currentPage: currentPage,
    })
    this.goToPage(currentPage);
  };

  download = (element) => {
    this.setState({
      showrefresh: 'visible',
    })
    console.log('element:', element);
    let mac = bigEndianToLittleEndian(element.macAddress);
    let OTApid = getOctets2Msg(transIntToHex2Str(element.pid));
    meshLog('OTApid', OTApid);
    //查版本
    const wangguan = JSON.parse(SPGet("wangguan"))
    const wangguanmac = bigEndianToLittleEndian(wangguan.macAddress)
    const OTAValue = -1000
    SPSet("OTAValue", JSON.stringify(OTAValue))
    SPSet("OTAMAC", JSON.stringify(mac))
    SPSet("OTApid", JSON.stringify(OTApid))

    meshLog('mac', mac);
    meshLog('wangguanmac', wangguanmac);
    let data1 = '252515'
    let data2 = '0000610000000000000F' + 'FFFFFFFFFFFF' + '00640000' + '0E00' //64是100的亮度值
    let data3 = sumHexBytes(data2) + '5252'
    let value = data1 + data2 + data3
    var data = '0,' + wangguanmac + ',' + value + ',';
    //发送数据
    PubSub.publish('showUpdate', data)//控制mqtt发信息
    meshLog('ota第一步，获取灯的版本的命令', data);
    PubSub.unsubscribe("OTAfrist")
    PubSub.subscribe('OTAfrist', (msg, datas) => {
      meshLog('msgdatas', datas);
      const vidNew = decimalToVersionString2(parseInt(getOctets2Msg(datas.slice(52, 56)), 16))
      meshLog('vidNew', vidNew);
      const firmware_version = JSON.parse(SPGet("firmware_version"))
      meshLog('firmware_version', firmware_version);
      const versionNew = firmware_version.slice(firmware_version.length - 6, firmware_version.length)
      meshLog('versionNew', versionNew.slice(0, 2));
      meshLog('versionNew1', vidNew[0]);
      if (vidNew[0] == versionNew.slice(0, 2) && vidNew[1] == versionNew.slice(2, 4) && vidNew[2] == versionNew.slice(4, 6)) {
        alert("No need for OTA")
      } else {
        var data = '2,' + wangguanmac + ',' + firmware_version + ',' + mac + ',';
        PubSub.publish('showUpdate', data)//控制mqtt发信息
        meshLog('需要ota',);
        // alert("请求已经发出")
      }

    })

    PubSub.unsubscribe("OTASecond")
    PubSub.subscribe('OTASecond', (msg, datas) => {
      meshLog('msgdatas', datas);
      const OTAPanduan = datas.slice(16, 18)
      meshLog('OTAPanduan', OTAPanduan);
      this.setState({
        showrefresh: 'hidden',
      })
      if (OTAPanduan == '00') {
        alert("OTA fail")
      } else {
        alert("OTA success")
      }

    })



  };

  render() {
    return (
      <div className="Sensor" >
        <div className="Sensorneirong">
          <div className="Sensorneirong1" >
            <div className="Sensormessage"  >
              <div className="Sensormessagetitle" >devices</div>
              <div className="Sensormessagedate" >
                <div className="Sensortitledate">
                  <div className="span1">Serial</div>
                  <div className="span11">Location</div>
                  <div className="span11">Device Type</div>
                  <div className="span11">Device Name</div>
                  <div className="span11">Version</div>
                  <div className="span11">OTA</div>
                </div>
                {
                  this.state.currentItems && this.state.currentItems.map((element, key) => {
                    if (!element.children) {
                      return (
                        <div className="Sensordatashuju" style={{ backgroundColor: key % 2 == 0 ? '' : '#F1F5FB' }} key={key}>
                          <div className="span2" >{key + 1}</div>
                          <div className="span22" >{getNameBygroupID(element.groupID)}</div>
                          <div className="span22" >Sensor</div>
                          <div className="span22" >{element.name}</div>
                          <div className="span22" >{decimalToVersionString(element.vid)}</div>
                          <div className="span22" onClick={() => { this.download(element) }}><a >OTA</a>
                          </div>
                        </div>
                      )
                    }
                    else {
                      return (
                        <span>{element}</span>
                      )
                    }
                  })
                }
              </div>
              <div className='zongyeshu'>
                <span style={{ marginLeft: 40 }}>共{this.state.totalPages}页</span>
                <label className="PerPage" for="PerPage">每页显示</label>
                <select id="PerPage" style={{ color: "#000000" }} name="PerPage">
                  <option value="10">15</option>
                  <option value="8">10</option>
                  <option value="5">5</option>
                </select>个
              </div>
              <div className='current'>
                <button disabled={this.state.currentPage === 1} onClick={() => { this.gotoFirstPage() }}>
                  首页
                </button>
                <button disabled={this.state.currentPage === 1} onClick={() => { this.goToPreviousPage() }}>
                  上一页
                </button>
                {Array.from({ length: this.state.totalPages }, (_, i) => (
                  <button
                    key={i}
                    onClick={() => { this.goToPage(i + 1) }}
                    style={{ margin: '2px' }}
                    disabled={this.state.currentPage === i + 1}
                  >
                    {i + 1}
                  </button>
                ))}
                <button disabled={this.state.currentPage === this.state.totalPages} onClick={() => { this.goToNextPage() }}>
                  下一页
                </button>
                <button disabled={this.state.currentPage === this.state.totalPages} onClick={() => { this.goToEndPage() }}>
                  末页
                </button>
                <span>&nbsp;&nbsp;共{this.state.totalPages}页&nbsp;&nbsp;</span>
                到 <input id='inputid' style={{ width: 30 }} type='number' min={1} ></input>页&nbsp;&nbsp;
                <button disabled={this.state.currentPage === this.state.totalPages} onClick={() => { this.changeTOPage() }}>
                  确定
                </button>
              </div>
            </div>
          </div>

        </div>
        <div style={{ position: 'absolute', zIndex: 3, left: 0, top: 0, width: '100%', height: '100%', visibility: this.state.showrefresh }}>
          <Refresh />
        </div>
      </div >

    )
  }
}
